/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package station;

import java.io.IOException;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.MulticastSocket;
import java.net.NetworkInterface;

/**
 *
 * @author safe
 */
public class Manager {

    private final String ip;
    private final int port;
    private final String stationClass;
    private final int utcOffset;
    private final String interfaceName;

    public Manager(String interfaceName, String ip, int port, String stationClass, int utcOffset) {
        this.interfaceName = interfaceName;
        this.ip = ip;
        this.port = port;
        this.stationClass = stationClass;
        this.utcOffset = utcOffset;
    }

    MulticastSocket initializeMulticast() {
        try {
            InetSocketAddress group = new InetSocketAddress(InetAddress.getByName(ip), port);
            MulticastSocket multicastsocket = new MulticastSocket(port);
            NetworkInterface networkInterface = NetworkInterface.getByName(interfaceName);
            multicastsocket.setNetworkInterface(networkInterface);
            multicastsocket.setTimeToLive(1);
            multicastsocket.joinGroup(group, networkInterface);
            multicastsocket.setLoopbackMode(false);

            return multicastsocket;
        } catch (IOException ex) {
//            TODO logger ansprechen um zeitintensives schreiben zu machen
            return null;
        }
    }

    private void start() {
        //       DataSlotBelegung.setNextSlot(10);
        DataAbweichungsZeit.setDiffTime(utcOffset);
        System.out.println("Station mit: "+ utcOffset + " Offset gestartet.");
        DataNaechsteNachricht.setStationClass(stationClass);
        DataNaechsteNachricht.setDestination(ip, port);
        DataAbweichungsZeit.setStationClass(stationClass);
        DataSlotBelegung.initializeSlots();
        MulticastSocket multicastSocket = initializeMulticast();
        MulticastListener multicastListener = new MulticastListener(multicastSocket);
        multicastListener.start();
        NutzdatenListener nutzatenListener = new NutzdatenListener();
        nutzatenListener.start();
        Taktgeber taktgeber = new Taktgeber(interfaceName, ip, port);
        taktgeber.start();
    }

//    <interface> <multicast-address> <receive-port> <station-index> <station-class> [ <UTC-offset-(ms)> ]
    public static void main(String[] args) {

        String interfaceName = args[0];
        String multicastAddress = args[1];
        int receivePort = Integer.parseInt(args[2]);
//        int stationIndex = Integer.parseInt(args[3]);
        String stationClass = args[3];
        int utcOffSet = 0;

        if (args.length > 4) {
            utcOffSet = Integer.parseInt(args[4]);
        }

        Manager manager = new Manager(interfaceName, multicastAddress, receivePort, stationClass, utcOffSet);
        manager.start();
    }
}
